<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, PieChart, LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { getInventoryOverview, getTopTen, getGoodsType, getInventoryTrend } from '@/api/echarts.js'
import { Goods, ShoppingCart, Money, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 注册必须的组件
echarts.use([TitleComponent, TooltipComponent, LegendComponent, GridComponent, BarChart, CanvasRenderer, PieChart, LineChart])

// 图表引用
const chartRef = ref(null)
const chartRef2 = ref(null)
const trendChartRef = ref(null)

// 数据控制
const timeRange = ref('month')
const sortBy = ref('stock')
const trendType = ref('in')
const dateRange = ref([])

// 概览卡片数据
const overviewCards = ref([
    { label: '总库存商品', value: '0', icon: 'Goods', color: '#409EFF' },
    { label: '本月入库', value: '0', icon: 'ShoppingCart', color: '#67C23A' },
    { label: '本月出库', value: '0', icon: 'Money', color: '#E6A23C' },
    { label: '库存预警', value: '0', icon: 'Warning', color: '#F56C6C' }
])

// 初始化图表
onMounted(() => {
    initCharts()
    getOverviewData()
    getTopTenData()
    getGoodsTypeData()
    window.addEventListener('resize', handleResize)
})

// 监听数据变化
watch([timeRange, sortBy, trendType, dateRange], () => {
    if (timeRange.value) {
        getGoodsTypeData()
    }
    if (sortBy.value) {
        getTopTenData()
    }
    if (dateRange.value?.length === 2) {
        getTrendData()
    }
})

// 初始化图表
const initCharts = () => {
    // 库存前十图表
    const myChart = echarts.init(chartRef.value)
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
                interval: 0,
                rotate: 30
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '库存',
            type: 'bar',
            data: [],
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#83bff6' },
                    { offset: 0.5, color: '#188df0' },
                    { offset: 1, color: '#188df0' }
                ])
            }
        }]
    }
    myChart.setOption(option)

    // 分类占比图表
    const myChart2 = echarts.init(chartRef2.value)
    const option2 = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [{
            name: '分类占比',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '20',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: []
        }]
    }
    myChart2.setOption(option2)

    // 趋势图表
    const trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['入库量', '出库量']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '入库量',
                type: 'line',
                data: [],
                smooth: true,
                itemStyle: {
                    color: '#67C23A'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#67C23A' },
                        { offset: 1, color: '#ffffff' }
                    ])
                }
            },
            {
                name: '出库量',
                type: 'line',
                data: [],
                smooth: true,
                itemStyle: {
                    color: '#E6A23C'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#E6A23C' },
                        { offset: 1, color: '#ffffff' }
                    ])
                }
            }
        ]
    }
    trendChart.setOption(trendOption)
}

// 获取数据
const getOverviewData = async () => {
    try {
        const res = await getInventoryOverview()
        if (res.code === 0) {
            overviewCards.value[0].value = res.data.totalProducts.toLocaleString()
            overviewCards.value[1].value = res.data.monthlyInbound.toLocaleString()
            overviewCards.value[2].value = res.data.monthlyOutbound.toLocaleString()
            overviewCards.value[3].value = res.data.warningCount.toLocaleString()
        }
    } catch (error) {
        console.error('获取概览数据失败:', error)
    }
}

const getTopTenData = async () => {
    try {
        const res = await getTopTen({ sortBy: sortBy.value })
        if (res.code === 0) {
            const chart = echarts.getInstanceByDom(chartRef.value)
            chart.setOption({
                xAxis: {
                    data: res.data.goodsName
                },
                series: [{
                    data: res.data.goodsAmount
                }]
            })
        }
    } catch (error) {
        console.error('获取前十数据失败:', error)
    }
}

const getGoodsTypeData = async () => {
    try {
        const res = await getGoodsType(timeRange.value)
        if (res.code === 0) {
            const chart = echarts.getInstanceByDom(chartRef2.value)
            chart.setOption({
                series: [{
                    data: res.data
                }]
            })
        }
    } catch (error) {
        console.error('获取分类占比数据失败:', error)
    }
}

const getTrendData = async () => {
    try {
        if (!dateRange.value || dateRange.value.length !== 2) return
        
        // 获取入库数据
        const inboundData = await getInventoryTrend({
            type: 'in',
            startTime: dateRange.value[0],
            endTime: dateRange.value[1]
        })
        
        // 获取出库数据
        const outboundData = await getInventoryTrend({
            type: 'out',
            startTime: dateRange.value[0],
            endTime: dateRange.value[1]
        })
        
        if (inboundData.code === 0 && outboundData.code === 0) {
            const trendChart = echarts.getInstanceByDom(trendChartRef.value)
            trendChart.setOption({
                xAxis: {
                    data: inboundData.data.dates
                },
                series: [
                    {
                        name: '入库量',
                        data: inboundData.data.values
                    },
                    {
                        name: '出库量',
                        data: outboundData.data.values
                    }
                ]
            })
        }
    } catch (error) {
        console.error('获取趋势数据失败:', error)
        ElMessage.error('获取趋势数据失败')
    }
}

// 处理窗口大小变化
const handleResize = () => {
    const charts = [
        echarts.getInstanceByDom(chartRef.value),
        echarts.getInstanceByDom(chartRef2.value),
        echarts.getInstanceByDom(trendChartRef.value)
    ]
    charts.forEach(chart => chart && chart.resize())
}

// 组件卸载时清理
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
})
</script>

<template>
    <div class="stats-container">
        <!-- 数据概览卡片 -->
        <div class="overview-cards">
            <el-row :gutter="20">
                <el-col :span="6" v-for="(card, index) in overviewCards" :key="index">
                    <el-card shadow="hover" class="overview-card">
                        <div class="card-content">
                            <div class="icon-wrapper" :style="{ backgroundColor: card.color + '20' }">
                                <el-icon :style="{ color: card.color }"><component :is="card.icon" /></el-icon>
                            </div>
                            <div class="info">
                                <div class="value">{{ card.value }}</div>
                                <div class="label">{{ card.label }}</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <template #header>
                            <div class="card-header">
                                <span>商品分类库存占比</span>
                                <el-radio-group v-model="timeRange" size="small">
                                    <el-radio-button label="week">本周</el-radio-button>
                                    <el-radio-button label="month">本月</el-radio-button>
                                    <el-radio-button label="year">全年</el-radio-button>
                                </el-radio-group>
                            </div>
                        </template>
                        <div ref="chartRef2" class="chart-container"></div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <template #header>
                            <div class="card-header">
                                <span>库存前十的商品</span>
                                <el-select v-model="sortBy" size="small" style="width: 120px">
                                    <el-option label="库存量" value="stock" />
                                    <el-option label="销售额" value="sales" />
                                </el-select>
                            </div>
                        </template>
                        <div ref="chartRef" class="chart-container"></div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 趋势图表 -->
        <div class="trend-section">
            <el-card shadow="hover" class="trend-card">
                <template #header>
                    <div class="card-header">
                        <span>库存变化趋势</span>
                        <div class="header-actions">
                            <el-date-picker
                                v-model="dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD"
                                :shortcuts="[
                                    {
                                        text: '最近一周',
                                        value: () => {
                                            const end = new Date()
                                            const start = new Date()
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                                            return [start, end]
                                        }
                                    },
                                    {
                                        text: '最近一个月',
                                        value: () => {
                                            const end = new Date()
                                            const start = new Date()
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                                            return [start, end]
                                        }
                                    },
                                    {
                                        text: '最近三个月',
                                        value: () => {
                                            const end = new Date()
                                            const start = new Date()
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                                            return [start, end]
                                        }
                                    }
                                ]"
                                size="small"
                                style="width: 300px"
                            />
                        </div>
                    </div>
                </template>
                <div ref="trendChartRef" class="trend-chart-container"></div>
            </el-card>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.stats-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;

    .overview-cards {
        margin-bottom: 20px;

        .overview-card {
            .card-content {
                display: flex;
                align-items: center;
                gap: 20px;

                .icon-wrapper {
                    width: 48px;
                    height: 48px;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .el-icon {
                        font-size: 24px;
                    }
                }

                .info {
                    .value {
                        font-size: 24px;
                        font-weight: bold;
                        line-height: 1;
                        margin-bottom: 5px;
                    }

                    .label {
                        font-size: 14px;
                        color: #909399;
                    }
                }
            }
        }
    }

    .charts-section {
        margin-bottom: 20px;

        .chart-card {
            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    font-size: 16px;
                    font-weight: bold;
                }
            }

            .chart-container {
                height: 400px;
            }
        }
    }

    .trend-section {
        margin-top: 20px;
        
        .trend-card {
            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                
                span {
                    font-size: 16px;
                    font-weight: bold;
                }
                
                .header-actions {
                    display: flex;
                    gap: 10px;
                }
            }
            
            .trend-chart-container {
                height: 400px;
                margin-top: 20px;
            }
        }
    }
}
</style>